package com.LeeCode;

/**
 * 单字符重复子串的最大长度
 */

public class Code1156 {
    public static void main(String[] args) {
        String text = "aaabaaa";
        System.out.println(new Code1156().maxRepOpt1(text));
    }

    public int maxRepOpt1(String text) {
        char[] chars = text.toCharArray();
        int[] cnt = new int[26], window = new int[26];
        for (char c : chars) {
            cnt[c - 'a']++;
        }

        int ans = 0, left = 0, size = 0;
        for (int right = 0; right < chars.length; right++) {
            if (window[chars[right] - 'a']++ == 0)
                size++;

            while (size > 2 || (size == 2 && window[chars[right] - 'a'] >= 2 && right - left + 1 - window[chars[right] - 'a'] > 1)) {
                if (--window[chars[left++] - 'a'] == 0)
                    size--;
            }

            int replace = 0;
            if (size == 1 ||
                    window[chars[right] - 'a'] > 1 && cnt[chars[right] - 'a'] - window[chars[right] - 'a'] >= 1 ||
                    window[chars[right] - 'a'] == 1 && cnt[chars[right - 1] - 'a'] - window[chars[right - 1] - 'a'] >= 1
            ) {
                replace = 1;
            }

            ans = Math.max(ans, right - left + replace);
        }
        return ans;
    }
}
